package engine.game.gfx;

import engine.game.Game;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.Serializable;
import javax.swing.ImageIcon;

public class ColoredSprite implements Renderable, Serializable {

    private int color;
    private int[][] pixels;
    private final int width;
    private final int height;
    private final Sprite sprite;

    public ColoredSprite(Sprite sprite, int color) {
        this.sprite = sprite;
        this.color = color;
        this.width = sprite.width();
        this.height = sprite.height();

        pixels = new int[sprite.width()][sprite.height()];
        for (int i = 0; i < pixels.length; i++) {
            for (int j = 0; j < pixels[0].length; j++) {
                this.pixels[i][j] = ((color >> sprite.pixels()[i][j] * 8)) & 255;
            }
        }
    }

    public Sprite sprite() {
        return sprite;
    }

    public int color() {
        return color;
    }

    @Override
    public int[][] pixels() {
        return pixels;
    }

    public int width() {
        return width;
    }

    public int height() {
        return height;
    }

    public void setColors(int newColor) {
        this.color = newColor;
        pixels = new int[sprite.width()][sprite.height()];
        for (int i = 0; i < pixels.length; i++) {
            for (int j = 0; j < pixels[0].length; j++) {
                this.pixels[i][j] = ((newColor >> sprite.pixels()[i][j] * 8)) & 255;
            }
        }
    }
    
    public ColoredSprite flip(boolean flipX, boolean flipY) {
        return new ColoredSprite(sprite.flip(flipX, flipY), color);
    }
    
    public ImageIcon getImageIcon(int scale, Color background) {
        BufferedImage bufferedIconImage = new BufferedImage(this.width(), this.height(), BufferedImage.TYPE_INT_RGB);
        int imagePixels[] = ((DataBufferInt) bufferedIconImage.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < this.pixels().length; i++) {
            for (int j = 0; j < this.pixels()[0].length; j++) {
                if (this.pixels()[i][j] < 255) {
                    imagePixels[i + (j * this.width())] = Game.colors[this.pixels()[i][j]];
                }
                else {
                    imagePixels[i + (j * this.width())] = background.hashCode();
                }
            }
        }

        Image resizedImage = bufferedIconImage.getScaledInstance(this.width() * scale, this.height() * scale, Image.SCALE_SMOOTH);
        return new ImageIcon(resizedImage);
    }
}
